#include "MyLogger.hpp"

using std::cout;
using std::endl;

MyLogger * MyLogger::_pInstance = nullptr;
MyLogger * MyLogger::getInstance(){
    //防止自复制
    if(_pInstance == nullptr){
        _pInstance = new MyLogger();
    }
    return _pInstance;
}

void MyLogger::warn(const char *msg){
    _mycat.warn(msg);
}
void MyLogger::error(const char *msg){
    _mycat.error(msg);
}
void MyLogger::debug(const char *msg){
    _mycat.debug(msg);
}
void MyLogger::info(const char *msg){
    _mycat.info(msg);
}

void MyLogger::destory(){
    if(_pInstance){
        LogInfo("MyLog destory");
        delete _pInstance;
        _pInstance = nullptr;
    }
}

MyLogger::MyLogger()
: _mycat(log4cpp::Category::getInstance("mycat"))//记录器，没有创建root对象，会隐式的创建一个root对象
{
    //1 设置布局
    log4cpp::PatternLayout * pnt1 = new log4cpp::PatternLayout();
    pnt1->setConversionPattern("%d %c [%p] %m%n");
    log4cpp::PatternLayout * pnt2 = new log4cpp::PatternLayout();
    pnt2->setConversionPattern("%d %c [%p] %m%n");
    log4cpp::PatternLayout * pnt3 = new log4cpp::PatternLayout();
    pnt3->setConversionPattern("%d %c [%p] %m%n");

    //2 创建输出器对象，与布局绑定
    log4cpp::OstreamAppender * pos = new log4cpp::OstreamAppender("console", &cout);//屏幕输出
    pos->setLayout(pnt1);
    log4cpp::FileAppender * filePos = new log4cpp::FileAppender("file", "mylog.log");//文件日志输出
    filePos->setLayout(pnt2);
    log4cpp::RollingFileAppender * rollingfilePos = new log4cpp::RollingFileAppender("rollingfile", 
                                                                                 "rollingfile.log",
                                                                                 5 * 1024,
                                                                                 9);//回卷文件日志输出
    rollingfilePos->setLayout(pnt3);

    //3 创建记录器(已创建)

    //4 给记录器设置优先级
    _mycat.setPriority(log4cpp::Priority::DEBUG);

    //5 给记录器设置输出器
    _mycat.setAppender(pos);
    _mycat.setAppender(filePos);
    _mycat.setAppender(rollingfilePos);

    //6 记录日志
    _mycat.info("Mylogger is create!");
    cout << "Mylogger()" << endl;

    //7 日志系统退出时，回收资源
}

MyLogger::~MyLogger(){
    _pInstance->_mycat.shutdown();
    cout << "~MyLogger()" << endl;
}